#coding=utf-8

# Author: Azhen,Nemo
# Email: azhenfeixue@gamil.com, nemo.zhp@gmail.com

# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.db.models import permalink
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import loader, Context, RequestContext
from meet001.meetup.forms import GroupCreateForm, RegisterForm
from meet001.meetup.forms import GroupSearchForm
from meet001.meetup.models import  Group, User, Membership
from meet001.meetup.location import location_code, city_district
from meet001.commentboard.models import CommentBoard
import urllib

ERRMSG_CREATOR_NOT_EXIST = '''创建者还未注册，花一分钟注册一个吧！'''

# handle /group/create/
# last changed by nemo.09-06-18

def create(request):
  anonymous = True
  if not request.user.is_anonymous():
    anonymous = False
  if request.method == "POST":
    form = GroupCreateForm(request.POST)
    if form.is_valid():
      
      id = form.save(request.user.username)
      add_member(id, request.user.id)
      return HttpResponseRedirect('/group/' + str(id) + '/')
    
    # here should show the error message!
    return render_to_response('meetup_group_create.html',   
       {'form': form, 'anonymous':anonymous, 
        'failed': True},
       context_instance=RequestContext(request))
  else:
    form = GroupCreateForm()
    return render_to_response('meetup_group_create.html',
        {'form': form, 'anonymous':anonymous, 
         'failed': False},
        context_instance=RequestContext(request))
# handler /group/search/
def search(request):
  anonymous = True
  if not request.user.is_anonymous():
    anonymous = False
  if request.method == "POST":
    search_result = None
    form = GroupSearchForm(request.POST)
    if form.is_valid():
      matched_groups = form.search()
      if matched_groups.count() > 0:
        search_result = matched_groups
        #return HttpResponseRedirect("/group/%s" %matched_groups[0].id)
    # If search failed.
    return render_to_response('meetup_group_search_result.html',
        {'form': form,
          'anonymous':anonymous,
          'failed': True,
          'search_result':search_result})
  else:
    form = GroupSearchForm()
    total_group_num = Group.objects.all().count()
    return render_to_response('meetup_group_search.html',
        {'form': form, 'total_group_num': total_group_num,
          'anonymous':anonymous, 'failed': False})


#added by zhangpeng
# handle group_details
# changed: display group using group id
def details(request, group_id=""):
  """display group page, and show special link for pages"""
  joined = False
  anonymous = True
  if not request.user.is_anonymous():
    anonymous = False
  if group_id:
    #find whether the group exist
    groups = Group.objects.filter(id=group_id)
    if groups:
      #if exists, display it
      if request.user in groups[0].users.all():
        joined = True
      #to see whether current user have already joined the group
      return render_to_response('meetup_group_details.html', 
          {'anonymous':anonymous,'joined':joined, 'user':request.user,
           'group':groups[0]},
          context_instance=RequestContext(request))
    else:
      #if not exist, show edit page
      form = GroupCreateForm()
      return HttpResponseRedirect('/groups/create/')
#      return render_to_response('meetup_group_create.html',
#          {'form': form, 'anonymous':anonymous, 
#           'failed': False})
  else:
    #show group search lists, to be defined
    form = GroupSearchForm()

    return HttpResponseRedirect('/groups/search/')
#    return render_to_response('meetup_group_search.html',
#        {'form': form, 'anonymous':anonymous, 
#         'failed': False})

# handle /thanks/
def thanks(request):
  return render_to_response('meetup_group_thanks.html', {}, context_instance=RequestContext(request))

# handle /join/
def join(request, usertype=0):
  if request.method == "POST":
    group = add_member(request.POST['group_id'], request.POST['user_id'], usertype)
    #after join, go to the group_details page
    return render_to_response('meetup_group_details.html', 
          {'anonymous':False,'joined':True,
           'group':group},
          context_instance=RequestContext(request))
  #if request not post method, we should return a group list
  return HttpResponseRedirect('/groups/search/')
 
  
#join a memeber into a group
#normal user type is 0
#admin type is 1, when the creation of group happens.
def add_member(group_id, user_id, usertype=0):
  new_user = User.objects.get(id=user_id)
  new_group = Group.objects.get(id=group_id)
  
  #to see whether the memebership is already exist
  if Membership.objects.filter(user=new_user, group=new_group).count() > 0 :
    return new_group
  new_membership = Membership()
  new_membership.user = User.objects.get(id=user_id)
  new_membership.group = Group.objects.get(id=group_id)
  new_membership.usertype = usertype
  new_membership.save()
  return new_membership.group

def create_plus_join(groupDict, user):
  
  #to see whether the group is already exist
  
  groups = Group.objects.filter(creator=user, name=groupDict['groupname'])
  if groups.count() > 0:
    return groups[0]
    
  new_group = Group()
  new_group.description = groupDict['description']
  new_group.creator = user
  new_group.name = groupDict['groupname']
  new_group.location = location_code[(groupDict['city'],
        groupDict['district'])] 
      
      #added member_limit and found_date
  new_group.member_limit = groupDict['member_limit']
  new_group.comment_board = CommentBoard.create_board()
  new_group.save()
  #add the creator as admin for the group
  add_member(new_group.id, user.id, 1)
  return new_group
